<template>
  <div>
    <Editor
      v-if="show"
      ref="editor"
      id="tinymce"
      v-model="html"
      :init="init"
      :disabled="readonly"
    ></Editor>
  </div>
</template>

<script>
// Import TinyMCE
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";

import "tinymce/icons/default";
// // 配置富文本
import "tinymce/themes/silver/theme.min.js"; //引入富文本的主要脚本
import "tinymce/plugins/image"; // 插入上传图片插件

import "tinymce/plugins/media"; // 插入视频插件

import "tinymce/plugins/table"; // 插入表格插件

import "tinymce/plugins/link"; //超链接插件
import "tinymce/plugins/autolink"; //超链接插件
import "tinymce/plugins/code"; //代码块插件

import "tinymce/plugins/lists"; // 列表插件

import "tinymce/plugins/contextmenu"; //右键菜单插件

import "tinymce/plugins/wordcount"; // 字数统计插件

import "tinymce/plugins/colorpicker"; //选择颜色插件

import "tinymce/plugins/textcolor"; //文本颜色插件

import "tinymce/plugins/fullscreen"; //全屏

import "tinymce/plugins/help"; // 帮助

import "tinymce/plugins/charmap";

import "tinymce/plugins/paste";

import "tinymce/plugins/print"; //打印

import "tinymce/plugins/preview"; // 预览

import "tinymce/plugins/hr"; // 水平线

import "tinymce/plugins/advlist";

import "tinymce/plugins/anchor";

import "tinymce/plugins/pagebreak";

import "tinymce/plugins/spellchecker";

import "tinymce/plugins/searchreplace";

import "tinymce/plugins/visualblocks";

import "tinymce/plugins/visualchars";

import "tinymce/plugins/insertdatetime";

import "tinymce/plugins/nonbreaking";

import "tinymce/plugins/autosave";

import "tinymce/plugins/codesample";

import "tinymce/plugins/fullpage";

import "tinymce/plugins/toc";

import "tinymce/plugins/directionality";
import "tinymce/plugins/imagetools";
import "tinymce/plugins/importcss";
import "tinymce/plugins/noneditable";
import "tinymce/plugins/save";
import "tinymce/plugins/tabfocus";
import "tinymce/plugins/template";
import "tinymce/plugins/textpattern";
import "tinymce/plugins/emoticons";

import "tinymce/plugins/media"; //媒体
import * as Constants from "@/constants/constants";
import ComponentApi from "@/api/components/component";
import val from "@/utils/utils";
import { Loading } from "element-ui";
let $Utils = val.instance;
let ossClient = null
const base64ToBlob = function(base64Data, fileType) {
  let bstr = atob(base64Data),
    l = bstr.length,
    u8Arr = new Uint8Array(l);
  while (l--) {
    u8Arr[l] = bstr.charCodeAt(l);
  }
  return new Blob([u8Arr], {
    type: fileType
  });
};
async function handleFileUpload(option) {
  return new Promise((resolve, reject) => {
    // https://vd3.bdstatic.com/mda-phi5hpizv58jhcpw/sc/cae_h264/1692428814851829651/mda-phi5hpizv58jhcpw.mp4?v_from_s=bdapp-bdappcore-feed-suzhou
    // 当前上传的文件
    console.log(option, "option");
    let file = null;
    let fileType = null;
    if (option instanceof File) {
      file = option;
      console.log(file);
      fileType = option.name.split("\.")[1];
      // size = file.size
    } else {
      // 注意:这里的option.blob()获取的文件是有问题的，base64是没有问题的,所以获取base64转为file
      fileType = option.filename().split("\.")[1];
      file = base64ToBlob(option.base64(), fileType);
    }

    const newName = $Utils.mathRand19() + "." + fileType;
    const storeAs = Constants.OSS_WEB_URL + "richText" + "/" + newName;
    ossClient
      .put(storeAs, file, {})
      .then(function(ret) {
        if (ret.res.statusCode === 200) {
          let realUrl = ret.url.replace(
            Constants.OSS_URL,
            Constants.OSS_REAL_URL
          );
          ret.url = realUrl;
          // 值回传
          option.response = ret;
          resolve(ret);
        } else {
          reject("上传失败");
        }
      })
      .catch(function(err) {
        reject(err);
      });
  });
}
export default {
  props: {
    richText: {
      type: String
    },
    readonly: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: "请输入详情描述"
    },
    height: {
      type: String,
      default: "500px"
    },
    width: {
      type: String,
      default: "100%"
    },
    menubar: {
      type: String,
      default: "file edit  view format table"
    },
    toolbar: {
      type: Array,
      default: () => [
        " searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript",
        "hr bullist numlist link  charmap preview  pagebreak insertdatetime  table emoticons forecolor backcolor link media image"
      ]
    },
    plugins: {
      type: Array,
      default: () => [
        "advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime  lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks emoticons link visualchars wordcount"
      ]
    }
  },
  watch: {
    richText(val) {
      this.html = val;
      console.log(this.html);
    },
    html(val) {
      this.$emit("getRichText", val);
    }
  },
  data() {
    return {
      html: "",
      ossClient: "",
      show: false,
      init: {
        skin_url: "/static/tinymce/skins/ui/oxide",
        language_url: "/static/tinymce/lang/zh_CN.js",
        language: "zh_CN",
        readonly: true,
        content_css: "/static/tinymce/skins/content/default/content.css",
        menubar: "file edit  view format table",
        toolbar: [
          " searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript",
          "hr bullist numlist link  charmap preview  pagebreak insertdatetime  table emoticons forecolor backcolor image"
        ],
        plugins: [
          "advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks emoticons visualchars wordcount"
        ],
        height: "500px",
        placeholder: "",
        emoticons_database_url: import('tinymce/plugins/emoticons/js/emojis.js'), //这里的emojis需要拿出来
        content_style: "img {max-width:320px;height:auto;vertical-align:top}",
        powerpaste_word_import: "merge", // 是否保留word粘贴样式  clean | merge
        advlist_bullet_styles: "square", // 无序列表 有序列表
        accept: "image/jpeg, image/png", // 设置图片上传规则
        images_upload_handler: async function (blobInfo, success, failure) {
          handleFileUpload(blobInfo).then(res => {
            success(res.url);
          });
        },
        file_picker_callback: function (callback, value, meta) {
          if (meta.filetype === "media") {
            // 模拟上传本地视频
            let input = document.createElement("input");
            input.setAttribute("type", "file");
            input.setAttribute("accept", "video/*");

            input.onchange = function () {
              let file = this.files[0];

              this.loadingInstance = Loading.service({text: "获取视频中"});
              if (file.size > 40960000) {
                // 不能超过 20971520即20兆
                this.loadingInstance.close();
                this.$message.error("不可以超过40MB");
                return;
              }
              handleFileUpload(file)
                .then(res => {
                  console.log(res.url);
                  this.loadingInstance.close();
                  callback(res.url);
                })
                .catch(err => {
                  this.loadingInstance.close();
                });
              // let fd = new FormData();
              // fd.append("img", file);
              // _this.$axios.post("/sbr/match/uploadImg", fd).then((res) => {
              //     let rr = res.data.data;
              //     callback(rr.filePath);
              // });
            };
            input.click();
          }
        },
        statusbar: false, // 隐藏编辑器底部的状态栏
        elementpath: false, // 禁用编辑器底部的状态栏
        paste_data_images: true // 允许粘贴图像
      }
    };
  },
  components: {
    Editor
  },
  methods: {},
  updated() {
  },
  mounted() {
    ComponentApi.uploadOss().then(async res => {
      ossClient = (await import('ali-oss')).default({
        region: Constants.OSS_REGION,
        accessKeyId: res.data.accessKeyId,
        accessKeySecret: res.data.accessKeySecret,
        stsToken: res.data.securityToken,
        bucket: Constants.OSS_BUCKET
      });
    });

    const {
      init,
      placeholder,
      width,
      height,
      menubar,
      toolbar,
      plugins
    } = this;
    init.placeholder = placeholder;
    init.width = width;
    init.height = height;
    init.menubar = menubar;
    init.toolbar = toolbar;
    init.plugins = plugins;
    this.show = true;
    // console.dir(this.$refs.editor)
    // setTimeout(()=>{
    //     this.$refs.editor.init()
    // },1000)

    // this.$refs.editor.activeEditor.setContent(this.init)
  },
  beforeDestroy: function () {
  }
};
</script>
